
#  1.获取channel表对象
from apps.goods.models import GoodsChannel
def get_channel_dict():
    channels = GoodsChannel.objects.order_by("group_id", "sequence")
    # 1.1遍历这个channels的set
    channel_dict = {}
    for channel_ob in channels:
        # 1.2通过外键获取组id
        group_id = channel_ob.group_id
        # 拼接大字典的第一部分（遍历出来的组id有37个判断一下避免重复）
        if group_id not in channel_dict:
            channel_dict[group_id] = {"channels": [], "sub_cats": []}
        # 2.通过外键获取categore的一级目录
        cat1 = channel_ob.category
        channel_dict[group_id]["channels"].append({
            "id": cat1.id,
            "name": cat1.name,
            "url": channel_ob.url
        })
        # 3.通过cat1获取cat2通过cat2获取cat3

        for cat2 in cat1.subs.all():
            cat_list = []
            for cat3 in cat2.subs.all():
                cat3 = {"id": cat3.id, "name": cat3.name}
                cat_list.append(cat3)
            channel_dict[group_id]["sub_cats"].append({
                "id": cat2.id,
                "name": cat2.name,
                "sub_cats": [cat3 for cat3 in cat_list]})
    return channel_dict